<?php
/**
 * Created by PhpStorm.
 * User: SUNHUATAO
 * Desc: 新闻中心控制器
 */
namespace App\Modules\Manage\Http\Controllers;
use App\Http\Controllers\ManageController;
use App\Modules\Manage\Model\productCategoryModel;
use App\Modules\Manage\Model\productModel;
use App\Http\Requests;
use App\Modules\Manage\Http\Requests\productRequest;
use Illuminate\Http\Request;
use Theme;
class ProductController extends ManageController
{
    public function __construct()
    {
        parent::__construct();
        $this->initTheme('manage');
        $this->theme->set('manageType', 'product');

    }
    public function productList(Request $request, $upID)
    {
        $title = productCategoryModel::where('id',$upID)->first()->cate_name;
        if($upID == 1){
            $this->theme->setTitle('产品管理');
        }elseif($upID == 3){
            $this->theme->setTitle('页脚管理');
        }
        $arr = $request->all();
        $upID = intval($upID);

        $m = productCategoryModel::get()->toArray();
        $res = productCategoryModel::_reSort($m,$upID);

        $productList = productModel::whereRaw('1 = 1');

        if ($request->get('catID')) {


            $r = productCategoryModel::_children($m, $request->get('catID'));
            if (empty($r)) {
                $productList = $productList->where('product.cat_id', $request->get('catID'));
            } else {
                $catIds = array_merge($r, array($request->get('catID')));
                $productList = $productList->whereIn('product.cat_id', $catIds);
            }
        } else {

            $r = productCategoryModel::_children($m, $upID);
            $catIds = array_merge($r, array($upID));
            $productList = $productList->whereIn('product.cat_id', $catIds);

        }

        if ($request->get('artID')) {
            $productList = $productList->where('product.id', $request->get('artID'));
        }

        if ($request->get('title')) {
            $productList = $productList->where('product.title', 'like', "%" . e($request->get('title')) . '%');
        }

        if ($request->get('author')) {
            $productList = $productList->where('product.author', 'like', '%' . e($request->get('author')) . '%');
        }
        if($request->get('start')){
            $start = date('Y-m-d H:i:s',strtotime($request->get('start')));
            $productList = $productList->where('product.created_at','>',$start);
        }
        if($request->get('end')){
            $end = date('Y-m-d H:i:s',strtotime($request->get('end')));
            $productList = $productList->where('product.created_at','<',$end);
        }
        $by = $request->get('by') ? $request->get('by') : 'product.created_at';
        $order = $request->get('order') ? $request->get('order') : 'desc';
        $paginate = $request->get('paginate') ? $request->get('paginate') : 10;


        $list = $productList->join('product_category as c', 'product.cat_id', '=', 'c.id')
            ->select('product.id', 'product.cat_id', 'product.title', 'product.view_times', 'product.author', 'product.created_at', 'c.cate_name as cate_name')
            ->orderBy($by, $order)->paginate($paginate);
        $listArr = $list->toArray();

        $data = array(
            'merge' => $arr,
            'upID' => $upID,
            'artID' => $request->get('artID'),
            'title' => $request->get('title'),
            'catID' => $request->get('catID'),
            'author' => $request->get('author'),
            'paginate' => $request->get('paginate'),
            'order' => $request->get('order'),
            'by' => $request->get('by'),
            'product_data' => $listArr,
            'product' => $list,
            'category' => $res

        );
        return $this->theme->scope('manage/product.productlist', $data)->render();

    }


    public function productDelete($id, $upID)
    {
        $upID = intval($upID);
        switch($upID){
            case 1:
                $url = '/manage/product/';
                break;
            case 3:
                $url = '/manage/productFooter/';
                break;
            default:
                $url = '/manage/product/';
        }
        $result = productModel::where('id', $id)->delete();
        if (!$result) {
            return redirect()->to($url . $upID)->with(array('message' => '操作失败'));
        }
        return redirect()->to($url . $upID)->with(array('message' => '操作成功'));

    }


    public function allDelete(Request $request)
    {
        $data = $request->except('_token');

        $res = productModel::destroy($data);
        if ($res) {
            return redirect()->to('/manage/product/1')->with(array('message' => '操作成功'));
        }
        return redirect()->to('/manage/product/1')->with(array('message' => '操作失败'));
    }


    public function addProduct(Request $request, $upID)
    {
        $upID = intval($upID);

        $title = productCategoryModel::where('id',$upID)->first()->cate_name;
        $this->theme->setTitle('文章新建');

        $m = productCategoryModel::get()->toArray();
        $res = productCategoryModel::_reSort($m,$upID);
        $parentCate = productCategoryModel::where('id',$upID)->first();
        $data = array(
            'category' => $res,
            'parent_cate' => $parentCate,
            'upID' => $upID
        );
        return $this->theme->scope('manage/product.addproduct', $data)->render();
    }


    public function postproduct(Request $request)
    {
        $data = $request->except('_token', 'pic','upID');
        $file = $request->file('cover');
        $data['cover_pic'] = $this->uploadPic($file);
        $upID = $request->get('upID');
        switch($upID){
            case 1:
                $url = '/manage/product/';
                break;
            case 3:
                $url = '/manage/productFooter/';
                break;
            default:
                $url = '/manage/product/';
        }
        $data['cat_id'] = $data['catID'];
        $data['created_at'] = date('Y-m-d H:i:s',time());
        $data['updated_at'] = date('Y-m-d H:i:s',time());
        $data['display_order'] = $request->get('displayOrder');
        $data['content'] = htmlspecialchars($data['content']);
        if(mb_strlen($data['content']) > 4294967295/3){
            $error['content'] = '文章内容太长，建议减少上传图片';
            if (!empty($error)) {
                return redirect('/manage/addProduct')->withErrors($error);
            }
        }

        $res = productModel::create($data);
        if ($res) {
            return redirect($url . $upID)->with(array('message' => '操作成功'));
        }
        return false;
    }


    public function editProduct(Request $request, $id, $upID)
    {
        $id = intval($id);
        $upID = intval($upID);

        $title = productCategoryModel::where('id',$upID)->first()->cate_name;
        $this->theme->setTitle($title);
        $arr = productCategoryModel::where('pid', $upID)->get()->toArray();
        foreach ($arr as $k => &$v) {
            $res = productCategoryModel::where('pid', $v['id'])->get()->toArray();
            $arr[$k]['res'] = $res;
        }

        $m = productCategoryModel::get()->toArray();
        $res = productCategoryModel::_reSort($m,$upID);
        $parentCate = productCategoryModel::where('id',$upID)->first();

        $product = productModel::where('id', $id)->first();
        $data = array(
            'product' => $product,
            'parent_cate' => $parentCate,
            'upID' => $upID,
            'cate' => $res
        );
        $this->theme->setTitle('页脚编辑');
        return $this->theme->scope('manage/product.editProduct', $data)->render();
    }


    public function postEditproduct(productRequest $request)
    {
        $data = $request->except('_token');
        $file = $request->file('cover');

        switch($data['upID']){
            case 1:
                $url = '/manage/product/';
                break;
            case 3:
                $url = '/manage/productFooter/';
                break;
            default:
                $url = '/manage/product/';
        }
        $data['content'] = htmlspecialchars($data['content']);
        if(mb_strlen($data['content']) > 4294967295/3){
            $error['content'] = '文章内容太长，建议减少上传图片';
            if (!empty($error)) {
                return redirect('/manage/addProduct')->withErrors($error);
            }
        }
        $arr = array(
            'title' => $data['title'],
            'cat_id' => $data['catID'],
            'author' => $data['author'],
            'display_order' => $data['displayOrder'],
            'content' => $data['content'],
            'summary' => $data['summary'],
            'seotitle' => $data['seotitle'],
            'keywords' => $data['keywords'],
            'description' => $data['description'],
            'updated_at' => date('Y-m-d H:i:s',time()),
        );
        $arr['cover_pic'] = $this->uploadPic($file);
        $res = productModel::where('id', $data['artID'])->update($arr);
        if ($res) {
            return redirect($url . $data['upID'])->with(array('message' => '操作成功'));
        }
    }

    public function uploadPic($file)
    {
        $allowed_extensions = ["png", "jpg", "gif"];
        if ($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
            return ['error' => 'You may only upload png, jpg or gif.'];
        }
        $destinationPath = 'storage/uploads/'.date('Y-m-d',time()).'/'; //public 文件夹下面建 storage/uploads 文件夹
        $extension = $file->getClientOriginalExtension();
        $fileName = str_random(10).'.'.$extension;
        $file->move($destinationPath, $fileName);
        $filePath = $destinationPath.$fileName;
        return $filePath;
    }

}
